package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.FavoriteDetail_z;
import com.scuec.groupfive.service.FavoriteDetailService_z;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/favorite/detail")
@CrossOrigin
public class FavoriteDetailController_z {
    private static final Logger logger = LoggerFactory.getLogger(FavoriteDetailController_z.class);

    @Autowired
    private FavoriteDetailService_z favoriteDetailService;

    @GetMapping("/questions")
    public ResponseEntity<Map<String, Object>> getFavoriteQuestions(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String query,
            @RequestParam Long userId,
            @RequestParam(required = false) Long folderId) {

        logger.info("Fetching favorite questions for userId: {}, page: {}, size: {}, query: {}, folderId: {}",
                userId, page, size, query, folderId);

        // 检查收藏总数
        int totalFavorites = favoriteDetailService.checkFavoriteCount(userId);
        logger.info("Total favorites for user {}: {}", userId, totalFavorites);

        // 检查活跃收藏数
        int activeFavorites = favoriteDetailService.checkActiveFavoriteCount(userId);
        logger.info("Active favorites for user {}: {}", userId, activeFavorites);

        List<FavoriteDetail_z> questions = favoriteDetailService.getFavoriteQuestions(userId, folderId, page, size, query);
        int total = favoriteDetailService.getFavoriteQuestionsCount(userId, folderId, query);

        logger.info("Found {} questions, total count: {}", questions.size(), total);

        // 添加详细的数据日志
        if (!questions.isEmpty()) {
            FavoriteDetail_z sample = questions.get(0);
            logger.info("Sample question data: questionId={}, year={}, originalSequence={}, subjectName={}, typeId={}, subjectId={}",
                    sample.getQuestionId(), sample.getYear(), sample.getOriginalSequence(),
                    sample.getSubjectName(), sample.getTypeId(), sample.getSubjectId());
        }

        Map<String, Object> response = new HashMap<>();
        response.put("content", questions);
        response.put("list", questions);  // 兼容前端可能使用的字段名
        response.put("currentPage", page);
        response.put("size", size);
        response.put("pageSize", size);   // 兼容前端可能使用的字段名
        response.put("totalElements", total);
        response.put("total", total);     // 兼容前端可能使用的字段名
        response.put("totalPages", (int) Math.ceil((double) total / size));

        return ResponseEntity.ok(response);
    }

    @GetMapping("/questions/{questionId}")
    public ResponseEntity<FavoriteDetail_z> getFavoriteQuestionDetail(
            @PathVariable Long questionId,
            @RequestParam Long userId) {

        logger.info("Fetching favorite question detail for userId: {}, questionId: {}", userId, questionId);

        FavoriteDetail_z questionDetail = favoriteDetailService.getFavoriteQuestionDetail(userId, questionId);

        if (questionDetail == null) {
            logger.warn("Question detail not found for userId: {}, questionId: {}", userId, questionId);
            return ResponseEntity.notFound().build();
        }

        logger.info("Found question detail: year={}, originalSequence={}, subjectName={}, typeId={}",
                questionDetail.getYear(), questionDetail.getOriginalSequence(),
                questionDetail.getSubjectName(), questionDetail.getTypeId());

        return ResponseEntity.ok(questionDetail);
    }

    @DeleteMapping("/questions/{questionId}")
    public ResponseEntity<Map<String, Object>> removeFavoriteQuestion(
            @PathVariable Long questionId,
            @RequestParam Long userId) {

        try {
            logger.info("Removing favorite question for userId: {}, questionId: {}", userId, questionId);
            favoriteDetailService.removeFavoriteQuestion(userId, questionId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "取消收藏成功");

            logger.info("Successfully removed favorite question for userId: {}, questionId: {}", userId, questionId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("Error removing favorite question for userId: {}, questionId: {}", userId, questionId, e);

            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消收藏失败: " + e.getMessage());

            return ResponseEntity.status(500).body(response);
        }
    }

    @GetMapping("/debug/user/{userId}")
    public ResponseEntity<Map<String, Object>> debugUserFavorites(@PathVariable Long userId) {
        logger.info("Debug: Checking favorites for user {}", userId);

        int totalFavorites = favoriteDetailService.checkFavoriteCount(userId);
        int activeFavorites = favoriteDetailService.checkActiveFavoriteCount(userId);
        List<FavoriteDetail_z> allFavorites = favoriteDetailService.getFavoriteDetails(userId);

        Map<String, Object> debug = new HashMap<>();
        debug.put("userId", userId);
        debug.put("totalFavorites", totalFavorites);
        debug.put("activeFavorites", activeFavorites);
        debug.put("favoritesList", allFavorites);

        logger.info("Debug results: totalFavorites={}, activeFavorites={}, listSize={}",
                totalFavorites, activeFavorites, allFavorites.size());

        return ResponseEntity.ok(debug);
    }
}